package tech.yilingyi.springdemo.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;

/**
 * Created by yinzuolong on 2016/12/26.
 */
public class MyCglibProxyObject implements MethodInterceptor {

    public ProductDao createCglibProxyObject() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(ProductDao.class);
        enhancer.setCallback(this);
        return (ProductDao) enhancer.create();
    }

    public Object intercept(Object proxy, Method method, Object[] args,
                            MethodProxy methodProxy) throws Throwable {
        Object o = null;
        if (method.isAnnotationPresent(Transactional.class)) {
            System.out.println("before ... ");
            o = methodProxy.invokeSuper(proxy, args);
            System.out.println("after ... ");
        } else {
            o = methodProxy.invokeSuper(proxy, args);
        }
        return o;
    }
}
